using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using RecommendedProduct;
using Rilisoft.MiniJson;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MarketController : EventCommander
{
	public const string productPath = "Product/";

	private const int approximateProductCount = 300;

	public const string categoryArmor = "Armor";

	public const string subCategoryBody = "Body";

	public const string subCategoryUtils = "Hidden";

	public const string subCategoryHats = "Hats";

	public const string subCategoryBoots = "Boots";

	public const string categoryLooks = "Looks";

	public const string subCategoryFemale = "Female";

	public const string subCategoryMale = "Male";

	public const string subCategorySpecial = "Special";

	public const string categoryRides = "Rides";

	public const string subCategoryBikes = "Bikes";

	public const string subCategoryCars = "Cars";

	public const string subCategoryTanks = "Tanks";

	public const string subCategoryTitans = "Titans";

	public const string categoryWeapon = "Weapons";

	public const string subCategoryGear = "Gear";

	public const string subCategoryMelee = "Melee";

	public const string subCategoryGuns = "Guns";

	public const string subCategoryRifles = "Rifles";

	public const string keyEquipedCar = "car";

	public const string keyEquipedSkin = "skin";

	public const string keyEquipedArmorBody = "body";

	public const string keyEquipedArmorHats = "hats";

	public const string keyEquipedArmorUtils = "utils";

	public const string keyEquipedArmorBoots = "boots";

	public const string keyEquipedVehicleSkin = "vehicleSkin";

	public const string categoryBest = "Best";

	public const string subCategoryBestWeapon = "Weapons";

	public const string subCategoryBestRides = "Rides";

	public const string subCategoryBestLooks = "Looks";

	public const string subCategoryBestArmor = "Armor";

	public const string categoryHidden = "Hidden";

	public const string subCategoryHidden = "Hidden";

	public const string subCategoryUpgrades = "Upgrades";

	public const string subCategoryVehicleSkins = "VehicleSkins";

	public const string subCategoryFreeUpgrades = "FreeVehicleUpgrades";

	private static MarketController instance;

	private Dictionary<string, Product> equipedProduct = new Dictionary<string, Product>();

	private MarketProductsHierarchy marketFolders;

	private ProductSet randomProductSet;

	public Dictionary<string, Product> allProducts;

	private bool slotSelected;

	private string selectedSlot;

	public bool marketOpened;

	private bool equipedArmorChanged;

	private bool equipedHatChanged;

	private bool equipedUtilsChanged;

	private bool equipedBootsChanged;

	private bool equipedCarChanged;

	public static string KEY_SELECTED_VEHICLE = "selectedVehicle";

	public static string keyCountBoost = "keyCountBoost";

	public static string keyCountCarBodyUp = "carBodyUpCount";

	public static string keyCountCarEngineUp = "carEngineUpCount";

	public static string keyCountCarIntakeUp = "carIntakeUpCount";

	public static string keyCountCarWheelsUp = "carWheelsUpCount";

	public static string keyCountTankBodyUp = "tankBodyUpCount";

	public static string keyCountTankEngineUp = "tankEngineUpCount";

	public static string keyCountTankDamageUp = "tankDamageUpCount";

	public static string keyCountTankWheelsUp = "tankWheelsUpCount";

	public static string keyCountMotoBodyUp = "motoBodyUpCount";

	public static string keyCountMotoEngineUp = "motoEngineUpCount";

	public static string keyCountMotoIntakeUp = "motoIntakeUpCount";

	public static string keyCountMotoWheelsUp = "motoWheelsUpCount";

	public static string keyCountTitanBodyUp = "titanBodyUp";

	public static string keyCountTitanEngineUp = "titanEngineUp";

	public static string keyCountTitanMainWeaponUp = "titanMainWeaponUp";

	public static string keyCountTitanAdditionalWeaponUp = "titanAdditionalWeaponUp";

	public static MarketController Instance
	{
		get
		{
			if (instance == null)
			{
				GameObject gameObject = new GameObject();
				gameObject.name = "MarketController";
				gameObject.AddComponent<MarketController>();
			}
			return instance;
		}
	}

	public MarketProductsHierarchy ProductHierarchy
	{
		get
		{
			return marketFolders;
		}
	}

	public Dictionary<string, Dictionary<string, Dictionary<string, Product>>> products
	{
		get
		{
			return ProductDB.products;
		}
		set
		{
			ProductDB.products = value;
		}
	}

	public event Action OnHideMarket;

	public override void Awake()
	{
		if (instance != null)
		{
			UnityEngine.Object.Destroy(this);
			return;
		}
		instance = this;
		UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
		LoadProducts();
		base.Awake();
	}

	private new void OnEnable()
	{
		MarketSaleController.marketSalesParsedFromJson += UpdateSaleCategory;
	}

	private new void OnDisable()
	{
		MarketSaleController.marketSalesParsedFromJson -= UpdateSaleCategory;
	}

	public override void Init()
	{
		base.Init();
		InitEvents(new string[4] { "WeaponEquipped", "WeaponUnEquipped", "SellectWeaponSlot", "ChangeConsumableCount" });
	}

	public string GetEquipedProduct(string category)
	{
		if (equipedProduct.ContainsKey(category))
		{
			if (equipedProduct[category] != null)
			{
				return equipedProduct[category].id;
			}
			return string.Empty;
		}
		return string.Empty;
	}

	public void SetWeaponSetForZombe(PunTeams.Team team, int graid, bool randomIfExist = false)
	{
		switch (team)
		{
		case PunTeams.Team.blue:
			if (randomProductSet == null || randomIfExist)
			{
				randomProductSet = ((ZombeSettings)settings.GetSettings(TypeGame.Zombe)).GetRandomSurvivorSet();
			}
			SelectWeaponSlot(GetMostExpensiveEquipedWeaponSlot());
			break;
		case PunTeams.Team.red:
			if (randomProductSet == null || randomIfExist)
			{
				randomProductSet = ((ZombeSettings)settings.GetSettings(TypeGame.Zombe)).GetRandomZombeSet();
			}
			foreach (SellectedProduct product in randomProductSet.products)
			{
				if (equipedProduct.ContainsKey(product.category))
				{
				}
				if (products["Weapons"].ContainsKey(product.category))
				{
					WeaponEquipped(product.category.ToLower(), (product.graid > graid) ? string.Empty : product.productId);
					if (product.productId != string.Empty && (product.graid == graid || team == PunTeams.Team.red))
					{
						SelectWeaponSlot(product.category.ToLower());
					}
				}
			}
			break;
		}
		string empty = string.Empty;
		SellectedProduct sellectedProduct = randomProductSet.products.Find((SellectedProduct x) => x.category == "Hats");
		empty = sellectedProduct.productId;
		if (empty == string.Empty)
		{
			empty = EquipmentManager.GetEquipedHatId;
		}
		EquipmentManager.LoadAndEquipHat((sellectedProduct.graid > graid) ? string.Empty : empty, PlayerBehavior.MyPlayer.equipmentManager);
		sellectedProduct = randomProductSet.products.Find((SellectedProduct x) => x.category == "Boots");
		empty = sellectedProduct.productId;
		if (empty == string.Empty)
		{
			empty = EquipmentManager.GetEquipedBootsId;
		}
		EquipmentManager.LoadAndEquipBoots((sellectedProduct.graid > graid) ? string.Empty : empty, PlayerBehavior.MyPlayer.equipmentManager);
		sellectedProduct = randomProductSet.products.Find((SellectedProduct x) => x.category == "Body");
		empty = sellectedProduct.productId;
		if (empty == string.Empty)
		{
			empty = EquipmentManager.GetEquipedArmorId;
		}
		EquipmentManager.LoadAndEquipArmor((sellectedProduct.graid > graid) ? string.Empty : empty, PlayerBehavior.MyPlayer.equipmentManager);
		sellectedProduct = randomProductSet.products.Find((SellectedProduct x) => x.category == "Hidden");
		EquipmentManager.LoadAndEquipUtils((sellectedProduct.graid > graid) ? string.Empty : sellectedProduct.productId, PlayerBehavior.MyPlayer.equipmentManager);
		sellectedProduct = randomProductSet.products.Find((SellectedProduct x) => x.category == "Looks");
		if (sellectedProduct.productId != string.Empty)
		{
			GameController.instance.playerScript.ChangeSkin(sellectedProduct.productId);
		}
		else
		{
			GameController.instance.playerScript.ChangeSkin(PlayerPrefs.GetString("skin"));
		}
	}

	public void SetWeaponSetForRobbers(bool equipWeaponsAndArmor)
	{
		BCWDebug.Log("LOG: SetWeaponSetForRobbers() called");
		string text = ((CopsRobbersSettings)settings.GetSettings(TypeGame.CopsAndRobbers)).robberSkins.RandomElement();
		if (text != string.Empty)
		{
			GameController.instance.playerScript.ChangeSkin(text);
		}
		else
		{
			GameController.instance.playerScript.ChangeSkin(PlayerPrefs.GetString("skin"));
		}
		if (!equipWeaponsAndArmor)
		{
			EquipmentManager.LoadAndEquipArmor(string.Empty, PlayerBehavior.MyPlayer.equipmentManager);
			EquipmentManager.LoadAndEquipHat(string.Empty, PlayerBehavior.MyPlayer.equipmentManager);
			EquipmentManager.LoadAndEquipBoots(string.Empty, PlayerBehavior.MyPlayer.equipmentManager);
			foreach (KeyValuePair<string, Dictionary<string, Product>> item in products["Weapons"])
			{
				WeaponEquipped(item.Key.ToLower(), (!(item.Key.ToLower() == "melee")) ? string.Empty : "knuckles");
			}
			SelectWeaponSlot("melee");
			GameController.instance.playerScript.weaponManager.ActivateWeaponSlot("melee");
		}
		else
		{
			PlayerBehavior.MyPlayer.equipmentManager.EquipAllItems();
			GetStartWeapons();
		}
	}

	public void SetWeaponSetForCops()
	{
		string text = ((CopsRobbersSettings)settings.GetSettings(TypeGame.CopsAndRobbers)).copSkins.RandomElement();
		if (text != string.Empty)
		{
			GameController.instance.playerScript.ChangeSkin(text);
		}
		else
		{
			GameController.instance.playerScript.ChangeSkin(PlayerPrefs.GetString("skin"));
		}
		PlayerBehavior.MyPlayer.equipmentManager.EquipAllItems();
		GetStartWeapons();
	}

	private void LoadProducts()
	{
		marketFolders = Resources.Load<MarketProductsHierarchy>("MarketFolders");
		allProducts = new Dictionary<string, Product>(300);
		ProductDB.GetProducts();
		foreach (KeyValuePair<string, Dictionary<string, Dictionary<string, Product>>> product in products)
		{
			foreach (KeyValuePair<string, Dictionary<string, Product>> item in product.Value)
			{
				foreach (KeyValuePair<string, Product> item2 in item.Value)
				{
					try
					{
						if (!string.IsNullOrEmpty(item2.Value.nextProductId))
						{
							item2.Value.nextProduct = item.Value[item2.Value.nextProductId];
						}
						if (!string.IsNullOrEmpty(item2.Value.prevProductId))
						{
							item2.Value.prevProduct = item.Value[item2.Value.prevProductId];
						}
					}
					catch
					{
						Debug.LogError("Do not find ugrade product " + item2.Value.id);
					}
					allProducts.Add(item2.Key, item2.Value);
					if (item2.Value.Best)
					{
						AddProductToBestCategory(item2.Value);
					}
				}
			}
		}
		SetEquipedWeapon();
		equipedProduct.Add("Rides", SetEquipedProduct("car", "Rides"));
		equipedProduct.Add("Body", SetEquipedProduct("body", "Armor"));
		equipedProduct.Add("Hats", SetEquipedProduct("hats", "Armor"));
		equipedProduct.Add("Boots", SetEquipedProduct("boots", "Armor"));
		SetEquipedSkin();
		SetEquippedVehicleSkins();
	}

	public void EquipNewProductsAfterReset()
	{
		equipedProduct.Clear();
		SetEquipedWeapon();
		equipedProduct.Add("Rides", SetEquipedProduct("car", "Rides"));
		equipedProduct.Add("Body", SetEquipedProduct("body", "Armor"));
		equipedProduct.Add("Hats", null);
		equipedProduct.Add("Boots", null);
		SetEquipedSkin();
		SetEquippedVehicleSkins();
	}

	private void AddProductToBestCategory(Product product)
	{
		if (product is ProductSkin)
		{
			products["Best"]["Looks"].Add(product.id, product);
		}
		else if (product is ProductWeapon || product is ProductComsumable)
		{
			products["Best"]["Weapons"].Add(product.id, product);
		}
		else if (product is ProductCar || product is ProductTank)
		{
			products["Best"]["Rides"].Add(product.id, product);
		}
		else if (product is ProductWearable)
		{
			products["Best"]["Armor"].Add(product.id, product);
		}
	}

	public void UpdateSaleCategory()
	{
		if (MarketSaleController.instance.EnableSalesInMarket)
		{
			ClearBestCategory();
			{
				foreach (Product value in allProducts.Values)
				{
					value.ApplySale();
					if (value.sale != null && value.SalePercent > 0f)
					{
						AddProductToBestCategory(value);
					}
				}
				return;
			}
		}
		ClearBestCategory();
		foreach (Product value2 in allProducts.Values)
		{
			if (value2.Best)
			{
				AddProductToBestCategory(value2);
			}
		}
	}

	private void ClearBestCategory()
	{
		products["Best"]["Looks"].Clear();
		products["Best"]["Weapons"].Clear();
		products["Best"]["Rides"].Clear();
		products["Best"]["Armor"].Clear();
	}

	private void ParseBestJSON(string text)
	{
		if (text.Equals(string.Empty))
		{
			return;
		}
		Dictionary<string, object> dictionary = Json.Deserialize(text) as Dictionary<string, object>;
		List<object> list = dictionary["P"] as List<object>;
		list.ForEach(delegate(object p)
		{
			Product value = null;
			if (allProducts.TryGetValue(p as string, out value))
			{
				value.SetBestProduct(true);
			}
			else
			{
				BCWDebug.LogError("Cannot find product with id " + p);
			}
		});
	}

	private void SetEquipedWeapon()
	{
		bool flag = !BCWStorage.Get<bool>("NewWeaponSaveMode");
		if (flag)
		{
			BCWStorage.Set("NewWeaponSaveMode", true);
		}
		foreach (KeyValuePair<string, Dictionary<string, Product>> item in products["Weapons"])
		{
			Product product = null;
			if (!PlayerPrefs.HasKey(item.Key.ToLower()))
			{
				product = (flag ? GetPurchasedProduct("Weapons", item.Key) : ((!item.Key.Equals("Melee")) ? GetPurchasedProduct("Weapons", item.Key) : GetProduct("Weapons", "Melee", "knuckles")));
			}
			else
			{
				try
				{
					product = item.Value[PlayerPrefs.GetString(item.Key.ToLower())];
				}
				catch
				{
					product = GetPurchasedProduct("Weapons", item.Key);
					BCWDebug.LogError("LOG: In " + item.Key.ToLower() + " save: " + PlayerPrefs.GetString(item.Key.ToLower()));
				}
			}
			equipedProduct.Add(item.Key, product);
			if (product != null)
			{
				Equip(product);
			}
		}
	}

	private Product GetPurchasedProduct(string cat, string subCat)
	{
		foreach (Product value in products[cat][subCat].Values)
		{
			if (value.Purchased)
			{
				return value;
			}
		}
		return null;
	}

	public void EquipPurchasedProduct(string cat, string subCat)
	{
		foreach (Product value in products[cat][subCat].Values)
		{
			if (value.Purchased)
			{
				Equip(value);
			}
		}
	}

	protected void SetEquipedSkin()
	{
		Product product = null;
		if (PlayerPrefs.HasKey("skin"))
		{
			product = GetProduct("Looks", PlayerPrefs.GetString("skin"));
		}
		else
		{
			int num = Load.LoadInt(settings.keyShooseSkin);
			string text = "shablon_" + ((num <= 9) ? "0" : string.Empty) + num;
			product = GetProduct("Looks", text);
			PlayerPrefs.SetString("skin", text);
		}
		product.SetEquiped();
		if (equipedProduct.ContainsKey("Looks"))
		{
			equipedProduct["Looks"] = product;
		}
		else
		{
			equipedProduct.Add("Looks", product);
		}
	}

	protected void SetEquippedVehicleSkins()
	{
		foreach (KeyValuePair<string, Dictionary<string, Product>> item in products["Rides"])
		{
			KeyValuePair<string, Product> vehicleProduct;
			foreach (KeyValuePair<string, Product> item2 in item.Value)
			{
				vehicleProduct = item2;
				string text = string.Empty;
				if (PlayerPrefs.HasKey("vehicleSkin_" + vehicleProduct.Value.id))
				{
					text = PlayerPrefs.GetString("vehicleSkin_" + vehicleProduct.Value.id);
				}
				if (text != string.Empty)
				{
					Product product = GetProduct("Hidden", text);
					if (product != null)
					{
						product.SetEquiped();
					}
					continue;
				}
				Product product2 = (from x in GetProducts("Hidden", "VehicleSkins").OfType<ProductVehicleSkin>()
					where x.targetId == vehicleProduct.Value.id
					select x).FirstOrDefault((ProductVehicleSkin x) => x.defaultSkin);
				if (product2 != null)
				{
					product2.Equip();
				}
			}
		}
	}

	private Product SetEquipedProduct(string key, string category)
	{
		if (PlayerPrefs.HasKey(key))
		{
			string @string = PlayerPrefs.GetString(key);
			if (!string.IsNullOrEmpty(@string))
			{
				Product product = GetProduct(category, @string);
				if (product == null)
				{
					BCWDebug.LogError("Cant find product " + @string + " in category " + category);
					PlayerPrefs.SetString(key, string.Empty);
					return null;
				}
				product.SetEquiped();
				return product;
			}
		}
		else
		{
			foreach (KeyValuePair<string, Dictionary<string, Product>> item in products[category])
			{
				foreach (KeyValuePair<string, Product> item2 in item.Value)
				{
					string text = settings.keyEquipGun + item2.Value.id;
					if (Load.LoadBool(text))
					{
						item2.Value.SetEquiped();
						PlayerPrefs.SetString(key, item2.Value.id);
						return item2.Value;
					}
				}
			}
			PlayerPrefs.SetString(key, string.Empty);
		}
		return null;
	}

	public ProductFreeUpgrade GetVehicleFreeUpgrade(ProductVehicleUpgrade vehicleUpgrade)
	{
		if (vehicleUpgrade == null)
		{
			return null;
		}
		ProductFreeUpgrade productFreeUpgrade = GetProducts("Hidden", "FreeVehicleUpgrades").OfType<ProductFreeUpgrade>().FirstOrDefault((ProductFreeUpgrade x) => x.upgradeType == vehicleUpgrade.upgradeType && x.vehicleType == vehicleUpgrade.targetType);
		if (productFreeUpgrade == null)
		{
			return null;
		}
		BCWDebug.Log("Count for " + productFreeUpgrade.ToString() + " is " + productFreeUpgrade.Count);
		return productFreeUpgrade;
	}

	public ProductVehicleSkin GetEquipedVehicleSkin(string carId)
	{
		IEnumerable<ProductVehicleSkin> source = from x in GetProducts("Hidden", "VehicleSkins").OfType<ProductVehicleSkin>()
			where x.targetId == carId
			select x;
		return source.FirstOrDefault((ProductVehicleSkin x) => x.Equipped);
	}

	public Product GetEquipedProduct(string category, string subCategory)
	{
		if (category.Equals("Weapons") || category.Equals("Armor"))
		{
			return equipedProduct[subCategory];
		}
		return (!equipedProduct.ContainsKey(category)) ? null : equipedProduct[category];
	}

	private void SetEquipedProduct(string category, string subCategory, Product product)
	{
		if (category.Equals("Weapons") || category.Equals("Armor"))
		{
			equipedProduct[subCategory] = product;
		}
		equipedProduct[category] = product;
		if (product == null || !category.Equals("Rides"))
		{
			return;
		}
		switch (subCategory)
		{
		case "Cars":
		{
			ProductCar productCar = (ProductCar)Instance.GetProduct(product.id);
			if (!productCar.notForRace)
			{
				settings.RaceCarName = product.id;
			}
			break;
		}
		case "Tanks":
			settings.SelectedTankName = product.id;
			break;
		case "Titans":
			settings.SelectedTitanName = product.id;
			break;
		}
	}

	public Product GetProduct(string id)
	{
		try
		{
			return allProducts[id];
		}
		catch
		{
			BCWDebug.LogError("Invalid product ID: " + id);
		}
		return null;
	}

	public Product GetProduct(string category, string id)
	{
		Product value = null;
		foreach (string key in products[category].Keys)
		{
			if (products[category][key].TryGetValue(id, out value))
			{
				break;
			}
		}
		return value;
	}

	public Product GetProduct(string category, string subCategory, string id)
	{
		try
		{
			return products[category][subCategory][id];
		}
		catch
		{
			return null;
		}
	}

	public List<Product> GetProducts(string category, string subCategory)
	{
		return products[category][subCategory].Values.ToList();
	}

	public Product GetFirstCarUpgrade(string carId, UpgradeType upgradeType)
	{
		string nameForUpgradeOfType = UpgradesDictionary.GetNameForUpgradeOfType(upgradeType, carId);
		return GetProduct("Hidden", "Upgrades", nameForUpgradeOfType);
	}

	private ProductVehicleUpgrade GetCurrentCarUpgrade(string carId, UpgradeType upgradeType)
	{
		string nameForUpgradeOfType = UpgradesDictionary.GetNameForUpgradeOfType(upgradeType, carId);
		Product product = GetProduct("Hidden", "Upgrades", nameForUpgradeOfType);
		if (product == null)
		{
			return null;
		}
		if (!product.Purchased)
		{
			return null;
		}
		while (product.nextProduct != null && product.nextProduct.Purchased)
		{
			product = product.nextProduct;
		}
		return product as ProductVehicleUpgrade;
	}

	public float GetCarUpgradeCoef(string carId, UpgradeType upgradeType)
	{
		ProductVehicleUpgrade currentCarUpgrade = GetCurrentCarUpgrade(carId, upgradeType);
		return (currentCarUpgrade != null) ? currentCarUpgrade.coef : 1f;
	}

	public bool HaveCarUpgrades(string carId)
	{
		return products["Hidden"]["Upgrades"].Values.Any((Product upgrade) => (upgrade as ProductVehicleUpgrade).targetId == carId);
	}

	public bool AllUpgradesAreBuyed(string carId)
	{
		if (HaveCarUpgrades(carId))
		{
			List<Product> source = products["Hidden"]["Upgrades"].Values.Where((Product upgrade) => (upgrade as ProductVehicleUpgrade).targetId == carId).ToList();
			return source.All((Product p) => p.Purchased);
		}
		return false;
	}

	public List<Product> GetListSortProducts(string category, string subCategory)
	{
		List<Product> list = new List<Product>();
		foreach (Product value in Instance.products[category][subCategory].Values)
		{
			if ((value.availableForBuy || value.Purchased || (value is ProductComsumable && (value as ProductComsumable).Count > 0)) && (value.nextProduct == null || !value.nextProduct.Purchased) && (value.prevProduct == null || value.Purchased) && (!(category == "Best") || (value.tier <= CupsManager.CurrentTier && (!MarketSaleController.instance.EnableSalesInMarket || value.sale != null))))
			{
				ProductVehicleUpgrade productVehicleUpgrade = value as ProductVehicleUpgrade;
				if (productVehicleUpgrade == null || !(productVehicleUpgrade.targetId != KEY_SELECTED_VEHICLE))
				{
					list.Add(value);
				}
			}
		}
		list.Sort((Product x, Product y) => x.sortWeight.CompareTo(y.sortWeight));
		return list;
	}

	public List<Product> GetProductListForTier(string category, string subCategory, int tier)
	{
		if (!Instance.products.ContainsKey(category))
		{
			BCWDebug.LogError("Products dictinary does't cointains category: " + category);
			return null;
		}
		if (!Instance.products[category].ContainsKey(subCategory))
		{
			BCWDebug.LogError("Products dictinary in catrgory " + category + " does't cointains subcategory: " + subCategory);
			return null;
		}
		List<Product> list = new List<Product>();
		foreach (Product value in Instance.products[category][subCategory].Values)
		{
			if (value.availableForBuy && tier == value.tier && (value.nextProduct == null || !value.nextProduct.Purchased) && (value.prevProduct == null || value.Purchased))
			{
				list.Add(value);
			}
		}
		return list;
	}

	private bool EnoughMoneyToBuy(Product product)
	{
		return (product.PriceIn.Equals(MoneyType.Cash) && settings.CathedExeptions >= product.Price) || (product.PriceIn.Equals(MoneyType.Gold) && settings.CathedWarnings >= product.Price);
	}

	public bool BuyProduct(string key, bool freeCost = false, int addCount = -1)
	{
		return BuyProduct(GetProduct(key), freeCost, addCount);
	}

	public bool BuyProduct(Product product, bool freeCost = false, int addCount = -1)
	{
		if (product.Purchased)
		{
			return false;
		}
		ProductFreeUpgrade vehicleFreeUpgrade = GetVehicleFreeUpgrade(product as ProductVehicleUpgrade);
		bool flag = vehicleFreeUpgrade != null && vehicleFreeUpgrade.Count > 0;
		if (freeCost || EnoughMoneyToBuy(product) || flag)
		{
			if (!freeCost)
			{
				if (product is ProductWeapon && product.prevProduct != null)
				{
					AllUnitaryAchievements.instance.upgradeGuns_5.Increment();
				}
				if (product is ProductCar || product is ProductTank)
				{
					AllUnitaryAchievements.instance.buyCars_5.Increment();
				}
			}
			if (product is ProductComsumable && (product as ProductComsumable).Count >= (product as ProductComsumable).maxCount)
			{
				return false;
			}
			if (!freeCost && !flag)
			{
				if (product.PriceIn == MoneyType.Cash)
				{
					settings.CathedExeptions -= product.Price;
				}
				else if (product.PriceIn == MoneyType.Gold)
				{
					settings.CathedWarnings -= product.Price;
				}
				settings.SaveCathedExeptionsToStorager();
				ProductPurchaseStatistic(product);
			}
			product.BuyProduct(addCount);
			if (VolumeController.IsSoundEnable && settings.thisScript != null && settings.thisScript.soundChangeMoney != null)
			{
				NGUITools.PlaySound(settings.thisScript.soundChangeMoney);
			}
			if (product.equippable && !freeCost)
			{
				Equip(product);
			}
			if (product.Purchased && RestorePurchases.instance != null)
			{
				RestorePurchases.instance.SavePurchase(product.id);
			}
			if (product is ProductVehicleUpgrade)
			{
				if (GameController.instance != null && GameController.instance.curTypeGame == TypeGame.TitanfallV2 && TitanSpawner.instance.currentTitan != null && TitanSpawner.instance.currentTitan.gameObject.name.Contains((product as ProductVehicleUpgrade).targetId))
				{
					TitanSpawner.instance.currentTitan.ApplyCarUpgradesRPC((product as ProductVehicleUpgrade).targetId);
				}
				if (PrivateCarManager.instance != null && PrivateCarManager.instance.currentCar != null && PrivateCarManager.instance.currentCar.gameObject.name.Contains((product as ProductVehicleUpgrade).targetId))
				{
					PrivateCarManager.instance.currentCar.ApplyCarUpgradesRPC((product as ProductVehicleUpgrade).targetId);
				}
			}
			if (product.prevProduct != null)
			{
				BuyProduct(product.prevProduct, freeCost);
			}
			ProductStaticManager.GetInstance().ClearAll();
			return true;
		}
		StartCoroutine(MarketControllerUI.instance.ShowBank(product.PriceIn));
		return false;
	}

	private void ProductPurchaseStatistic(Product product)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		dictionary.Add(FlurryWrapper.SubCategoryNameForFlurry(product), product.nameForFlurry);
		FlurryWrapper.LogEvent(FlurryWrapper.GetEventName(FlurryWrapper.EV_BUY_ITEM), dictionary);
		dictionary.Clear();
		if (Load.LoadBool(settings.keyPayment))
		{
			dictionary.Add("Payed", product.nameForFlurry);
		}
		else
		{
			dictionary.Add("Non-Payed", product.nameForFlurry);
		}
		FlurryWrapper.LogEvent(FlurryWrapper.EV_BUY_ITEM + "(general)", dictionary);
		dictionary.Clear();
		dictionary.Add("League " + (CupsManager.CurrentLeagueIndex + 1), product.nameForFlurry);
		FlurryWrapper.LogEvent(FlurryWrapper.EV_BUY_ITEM_LEAGUE + FlurryWrapper.LevelForFlurry(), dictionary);
		FlurryWrapper.LogEvent(FlurryWrapper.GetEventName(FlurryWrapper.EV_BUY_ITEM_LEAGUE) + FlurryWrapper.LevelForFlurry(), dictionary);
		if (product.SalePercent > 0f)
		{
			dictionary.Clear();
			dictionary.Add("Buying_item", product.nameForFlurry);
			FlurryWrapper.LogEvent(FlurryWrapper.EV_SALES_ITEMS, dictionary);
		}
		if (SceneManager.GetActiveScene().name != "Lobby")
		{
			dictionary.Clear();
			dictionary.Add("Total", product.nameForFlurry);
			dictionary.Add(FlurryWrapper.GetCurrentGameMode(), product.nameForFlurry);
			FlurryWrapper.LogEvent(FlurryWrapper.EV_CURENCY_IN_APPS_PURCHASES_ON_GAME_MODE, dictionary);
		}
		dictionary.Clear();
		dictionary.Add(FlurryWrapper.SubCategoryNameForFlurry(product), product.nameForFlurry);
		dictionary.Add("Total", product.nameForFlurry);
		switch (product.PriceIn)
		{
		case MoneyType.Cash:
			if (settings.CathedExeptions - Load.LoadInt(settings.keyBuyingCash) < product.Price)
			{
				Save.SaveInt(settings.keyBuyingCash, Load.LoadInt(settings.keyBuyingCash) - product.Price);
				if (Load.LoadInt(settings.keyBuyingCash) < 0)
				{
					Save.SaveInt(settings.keyBuyingCash, 0);
				}
			}
			if (Load.LoadBool(settings.KeyFirsPurchasedCash))
			{
				FlurryWrapper.LogEvent(FlurryWrapper.EV_FIRS_SHOP_FOR_PURCHASED_CASH, dictionary);
				Save.SaveBool(settings.KeyFirsPurchasedCash, false);
			}
			BCWStorage.Set(FlurryWrapper.EV_CASH_SPENDING_BY_TIER, BCWStorage.Get<int>(FlurryWrapper.EV_CASH_SPENDING_BY_TIER + product.Price));
			break;
		case MoneyType.Gold:
			if (settings.CathedWarnings - Load.LoadInt(settings.keyBuyingGold) < product.Price)
			{
				Save.SaveInt(settings.keyBuyingGold, Load.LoadInt(settings.keyBuyingGold) - product.Price);
			}
			if (Load.LoadBool(settings.KeyFirsPurchasedGold))
			{
				FlurryWrapper.LogEvent(FlurryWrapper.EV_FIRS_SHOP_FOR_PURCHASED_GOLD, dictionary);
				Save.SaveBool(settings.KeyFirsPurchasedGold, false);
			}
			BCWStorage.Set(FlurryWrapper.EV_GOLD_SPENDING_BY_TIER, BCWStorage.Get<int>(FlurryWrapper.EV_GOLD_SPENDING_BY_TIER + product.Price));
			break;
		}
		if (product.categoryName != "Looks" && product.subCategoryName != "Gear")
		{
			BCWStorage.Set(FlurryWrapper.EV_ITEM_QUANTITY_BY_TIER, BCWStorage.Get<int>(FlurryWrapper.EV_ITEM_QUANTITY_BY_TIER) + 1);
		}
		if (FlurryWrapper.activePlayer && !string.IsNullOrEmpty(FlurryWrapper.GetProductCategotyForFlurry(product)))
		{
			dictionary.Clear();
			dictionary.Add(FlurryWrapper.GetProductCategotyForFlurry(product), (!string.IsNullOrEmpty(product.nameForFlurry)) ? product.nameForFlurry : product.id);
			dictionary.Add("Total", (!string.IsNullOrEmpty(product.nameForFlurry)) ? product.nameForFlurry : product.id);
			FlurryWrapper.LogEvent(FlurryWrapper.EV_SHOP_PURCHASES_BY_ACTIVE_USERS + FlurryWrapper.GetPayingSuffix(), dictionary);
		}
	}

	public bool Equip(Product product)
	{
		if (product != null)
		{
			Product product2 = GetEquipedProduct(product.categoryName, product.subCategoryName);
			if (product2 != null)
			{
				if (product is ProductVehicleSkin)
				{
					if ((product as ProductVehicleSkin).targetId == (product2 as ProductVehicleSkin).targetId)
					{
						UnEquip(product2);
					}
				}
				else
				{
					UnEquip(product2);
				}
			}
			SetEquipedProduct(product.categoryName, product.subCategoryName, product);
			if (product.categoryName.Equals("Looks") && BCWServer.instance != null)
			{
				BCWServer.instance.UpdatePlayerData();
			}
			return product.Equip();
		}
		return false;
	}

	public void EquipBetter(Product product)
	{
		Product product2 = GetEquipedProduct(product.categoryName, product.subCategoryName);
		if (!(product is ProductBoost) && (product2 == null || (product.PriceIn.Equals(product2.PriceIn) && product.Price > product2.Price) || (!product.PriceIn.Equals(product2.PriceIn) && product.PriceIn.Equals(MoneyType.Cash) && product.Price * 25 > product2.Price) || (product.PriceIn.Equals(MoneyType.Gold) && product.Price > product2.Price * 25)))
		{
			if (product2 != null)
			{
				UnEquip(product2);
			}
			SetEquipedProduct(product.categoryName, product.subCategoryName, product);
			if (product.categoryName.Equals("Looks") && BCWServer.instance != null)
			{
				BCWServer.instance.UpdatePlayerData();
			}
			product.Equip();
			if (product.categoryName == "Weapons")
			{
				LobbyPlayerGunManager.ShowNewWeapon(product.id);
			}
		}
	}

	public bool Equip(string category, string id)
	{
		return Equip(GetProduct(category, id));
	}

	public bool UnEquip(Product product)
	{
		SetEquipedProduct(product.categoryName, product.subCategoryName, null);
		return product.UnEquip();
	}

	public bool UnEquip(string category, string id)
	{
		return UnEquip(GetProduct(category, id));
	}

	public bool UnEquip(string category, string subCategory, string id)
	{
		return UnEquip(GetProduct(category, subCategory, id));
	}

	public void WeaponEquipped(string slotName, string weaponName)
	{
		if (!settings.learningCompleted)
		{
			RiseEvent(this, "WeaponEquipped", slotName, string.Empty);
		}
		else
		{
			RiseEvent(this, "WeaponEquipped", slotName, weaponName);
		}
	}

	public void ChangeConsumableCount(string weaponName)
	{
		RiseEvent(this, "ChangeConsumableCount", weaponName);
	}

	public void GetStartWeapons()
	{
		foreach (KeyValuePair<string, Dictionary<string, Product>> item in products["Weapons"])
		{
			Product product = equipedProduct[item.Key];
			WeaponEquipped(item.Key.ToLower(), (product != null) ? product.id : string.Empty);
		}
		SelectWeaponSlot(GetMostExpensiveEquipedWeaponSlot());
	}

	public void SelectWeaponSlot(string slotName)
	{
		RiseEvent(this, "SellectWeaponSlot", slotName);
	}

	public void ChangeBoostCount(int count, int maxCount)
	{
		if (count > 0)
		{
			int num = BCWStorage.Get<int>(keyCountBoost);
			if (num + count < maxCount)
			{
				BCWStorage.Set(keyCountBoost, num + count);
			}
			else
			{
				BCWStorage.Set(keyCountBoost, maxCount);
			}
		}
	}

	public static void SaveFreeVehicleUpgradesCount(int add, int maxCount, string key)
	{
		int num = BCWStorage.Get<int>(key);
		BCWStorage.Set(key, Mathf.Clamp(num + add, 0, maxCount));
	}

	public void SetSelectedWeaponSlot(string slotName)
	{
		selectedSlot = slotName;
		slotSelected = true;
	}

	public void SelectedWeaponSlotIfSelected()
	{
		if (slotSelected)
		{
			SelectWeaponSlot(selectedSlot);
		}
	}

	public void SetSlotNotSelected()
	{
		slotSelected = false;
	}

	public string GetMostExpensiveEquipedWeaponSlot()
	{
		string result = string.Empty;
		int num = -1;
		foreach (KeyValuePair<string, Dictionary<string, Product>> item in products["Weapons"])
		{
			if (item.Key.Equals("Gear"))
			{
				continue;
			}
			Product product = equipedProduct[item.Key];
			if (product != null)
			{
				int num2 = ((product.PriceIn != MoneyType.Gold) ? product.Price : (product.Price * 15));
				if (num2 == 0 && num2 >= num)
				{
					result = "rifles";
				}
				else if (num2 > num)
				{
					num = num2;
					result = item.Key.ToLower();
				}
			}
		}
		return result;
	}

	public string GetRandomEquipedWeapon()
	{
		List<string> list = new List<string>();
		foreach (KeyValuePair<string, Dictionary<string, Product>> item in products["Weapons"])
		{
			if (equipedProduct[item.Key] != null)
			{
				list.Add(equipedProduct[item.Key].id);
			}
		}
		return list[UnityEngine.Random.Range(0, list.Count)];
	}

	public Product GetRandomEquipedWeaponProduct()
	{
		List<Product> list = new List<Product>();
		foreach (KeyValuePair<string, Dictionary<string, Product>> item in products["Weapons"])
		{
			if (equipedProduct[item.Key] != null)
			{
				list.Add(equipedProduct[item.Key]);
			}
		}
		return list[UnityEngine.Random.Range(0, list.Count)];
	}

	public void ShowMarket(Product product = null)
	{
		slotSelected = false;
		equipedCarChanged = false;
		equipedArmorChanged = false;
		equipedHatChanged = false;
		equipedBootsChanged = false;
		if (settings.offlineMode)
		{
			if (PlayerBehavior.MyPlayer.isGetOutCarForOffline)
			{
				StartCoroutine(WaitForOutFromMoto());
			}
			else
			{
				Time.timeScale = 0f;
			}
		}
		marketOpened = true;
		MarketControllerUI.instance.ShowMarket(product);
	}

	private IEnumerator WaitForOutFromMoto()
	{
		while (PlayerBehavior.MyPlayer.isGetOutCarForOffline)
		{
			yield return new WaitForSeconds(0.5f);
		}
		Time.timeScale = 0f;
	}

	public void ShowMarket(string id)
	{
		ShowMarket(GetProduct(id));
	}

	public void SendEquipedWeapon()
	{
		foreach (KeyValuePair<string, Dictionary<string, Product>> item in products["Weapons"])
		{
			Product product = equipedProduct[item.Key];
			WeaponEquipped(item.Key.ToLower(), (product != null) ? product.id : string.Empty);
		}
	}

	public void HideMarket()
	{
		if (!MarketControllerUI.instance.MarketActive())
		{
			return;
		}
		MarketControllerUI.instance.HideMarket();
		if (settings.offlineMode)
		{
			Time.timeScale = 1f;
		}
		marketOpened = false;
		if (GameController.instance != null && TDMController.instance != null && GameController.instance.curTypeGame == TypeGame.CopsAndRobbers && TDMController.myTeam == PunTeams.Team.blue && CopsAndRobbersController.instance != null && !CopsAndRobbersController.instance.pickedUpBonus)
		{
			return;
		}
		SendEquipedWeapon();
		if (slotSelected)
		{
			SelectWeaponSlot(selectedSlot);
		}
		if (GameController.instance != null && GameController.instance.playerScript != null)
		{
			if (GameController.instance.curTypeGame != TypeGame.CopsAndRobbers)
			{
				GameController.instance.playerScript.ChangeSkin(GetEquipedSkinID());
			}
			if (equipedArmorChanged)
			{
				PlayerBehavior.MyPlayer.equipmentManager.EquipCurrentArmor();
			}
			if (equipedHatChanged)
			{
				PlayerBehavior.MyPlayer.equipmentManager.EquipCurrentHat();
			}
			if (equipedBootsChanged)
			{
				PlayerBehavior.MyPlayer.equipmentManager.EquipCurrentBoots();
			}
			PlayerBehavior.MyPlayer.UpdateWearingPropsHashtable();
		}
		if (equipedCarChanged)
		{
			PrivateCarManager.instance.FindCurrentCar();
		}
		if (this.OnHideMarket != null)
		{
			this.OnHideMarket();
		}
	}

	public List<Product> GetListPurchasetCar()
	{
		List<Product> list = new List<Product>();
		foreach (Product value in products["Rides"]["Cars"].Values)
		{
			if (value.Purchased)
			{
				list.Add(value);
			}
		}
		return list;
	}

	public List<Product> GetListPurchasetTank()
	{
		List<Product> list = new List<Product>();
		foreach (Product value in products["Rides"]["Tanks"].Values)
		{
			if (value.Purchased)
			{
				list.Add(value);
			}
		}
		return list;
	}

	public List<Product> GetListPurchasetTitan()
	{
		List<Product> list = new List<Product>();
		foreach (Product value in products["Rides"]["Titans"].Values)
		{
			if (value.Purchased)
			{
				list.Add(value);
			}
		}
		return list;
	}

	public void EquipedArmorChanged()
	{
		equipedArmorChanged = true;
	}

	public void EquipedHatChanged()
	{
		equipedHatChanged = true;
	}

	public void EquipedUtilsChanged()
	{
		equipedUtilsChanged = true;
	}

	public void EquipedBootsChanged()
	{
		equipedBootsChanged = true;
	}

	public void EquipedCarChanged()
	{
		equipedCarChanged = true;
	}

	public Texture2D GetEquipedSkinTexture()
	{
		return (equipedProduct["Looks"] as ProductSkin).GetSkinTexture();
	}

	public string GetEquipedSkinID()
	{
		return equipedProduct["Looks"].id;
	}

	public Texture2D GetSkinTexture(string id)
	{
		return GetSkin(id).GetSkinTexture();
	}

	public bool IsFemaleSkin(string id)
	{
		return GetSkin(id).femaleSkin;
	}

	private ProductSkin GetSkin(string id)
	{
		return GetProduct("Looks", id) as ProductSkin;
	}

	public Texture2D GetProductTexture(Product product)
	{
		return Resources.Load<Texture2D>("AtlasShopGuns/" + product.texture);
	}

	public Texture2D GetProductTexture(string id)
	{
		return Resources.Load<Texture2D>("AtlasShopGuns/" + GetProduct(id).texture);
	}

	public Texture2D GetProductTextureExactForId(string id)
	{
		return Resources.Load<Texture2D>("AtlasShopGuns/" + id);
	}

	public void SetProductSaleInfo(string productID, float percent)
	{
		GetProduct(productID).SetSalePercent(percent);
	}

	public void ExportSkin(ProductSkin skin)
	{
		Texture2D skinTexture = skin.GetSkinTexture();
		SkinsManager.SaveTextureWithName(skinTexture, "upload_Skin.png", false);
		string text = Path.Combine(SkinsManager._PathBase, "upload_Skin.png");
		BCWDebug.Log("upload path=" + text);
		CookieContainer cookies = new CookieContainer();
		UploadFileEx(text, "http://d-games.org/uploadimg.php", "userfile", "image/png", cookies);
	}

	public static void UploadFileEx(string uploadfile, string url, string fileFormName, string contenttype, CookieContainer cookies)
	{
		WebClient webClient = new WebClient();
		if (fileFormName == null || fileFormName.Length == 0)
		{
			fileFormName = "file";
		}
		if (contenttype == null || contenttype.Length == 0)
		{
			contenttype = "application/octet-stream";
		}
		Uri requestUri = new Uri(url);
		string text = "----------" + DateTime.Now.Ticks.ToString("x");
		HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
		httpWebRequest.CookieContainer = cookies;
		httpWebRequest.ContentType = "multipart/form-data; boundary=" + text;
		httpWebRequest.Method = "POST";
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append("--");
		stringBuilder.Append(text);
		stringBuilder.Append("\r\n");
		stringBuilder.Append("Content-Disposition: form-data; name=\"");
		stringBuilder.Append(fileFormName);
		stringBuilder.Append("\"; filename=\"");
		stringBuilder.Append(Path.GetFileName(uploadfile));
		stringBuilder.Append("\"");
		stringBuilder.Append("\r\n");
		stringBuilder.Append("Content-Type: ");
		stringBuilder.Append(contenttype);
		stringBuilder.Append("\r\n");
		stringBuilder.Append("\r\n");
		string s = stringBuilder.ToString();
		byte[] bytes = Encoding.UTF8.GetBytes(s);
		byte[] bytes2 = Encoding.UTF8.GetBytes("\r\n--" + text + "\r\n");
		FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
		long contentLength = bytes.Length + fileStream.Length + bytes2.Length;
		httpWebRequest.ContentLength = contentLength;
		Stream requestStream = httpWebRequest.GetRequestStream();
		requestStream.Write(bytes, 0, bytes.Length);
		byte[] array = new byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
		int num = 0;
		while ((num = fileStream.Read(array, 0, array.Length)) != 0)
		{
			requestStream.Write(array, 0, num);
		}
		requestStream.Write(bytes2, 0, bytes2.Length);
		BCWDebug.Log("webrequest=" + httpWebRequest);
		WebResponse response;
		try
		{
			response = httpWebRequest.GetResponse();
		}
		catch
		{
			return;
		}
		Stream responseStream = response.GetResponseStream();
		StreamReader streamReader = new StreamReader(responseStream);
		string url2 = "http://www.minecraft.net/profile/skin/remote?url=" + streamReader.ReadToEnd();
		Application.OpenURL(url2);
	}

	public void SetEnemySkin(EnemyBehavior enemy, string id)
	{
		StartCoroutine(SetEnemySkinIEnumerator(enemy, id));
	}

	public IEnumerator SetEnemySkinIEnumerator(EnemyBehavior enemy, string id)
	{
		ResourceRequest resourse = Resources.LoadAsync<Texture2D>("Skins/" + id);
		yield return resourse;
		enemy.SetSkin(resourse.asset as Texture2D);
	}

	public Product GetRandomSkinCanGiveRandom()
	{
		List<Product> list = new List<Product>();
		foreach (Dictionary<string, Product> value in products["Looks"].Values)
		{
			foreach (Product value2 in value.Values)
			{
				if ((value2 as ProductSkin).CanGiveRandom)
				{
					list.Add(value2);
				}
			}
		}
		if (list.Count == 0)
		{
			return null;
		}
		return list[UnityEngine.Random.Range(0, list.Count)];
	}

	public static bool CanBuyProduct(Product product)
	{
		if (CupsManager.CurrentTier >= product.tier)
		{
			if (!product.Purchased)
			{
				if (product.availableForBuy)
				{
					return true;
				}
			}
			else if (product.nextProduct != null && !product.nextProduct.Purchased && CupsManager.CurrentTier >= product.nextProduct.tier)
			{
				return true;
			}
		}
		return false;
	}

	public bool IsMyTier(int league, int weaponTier)
	{
		List<int> records = ProductDB.GetRecords();
		int num = weaponTier;
		int num2 = 0;
		for (int num3 = records.Count - 1; num3 >= 0; num3--)
		{
			if (league >= records[num3])
			{
				num2++;
				num = records[num3];
			}
			if (num2 >= 1)
			{
				break;
			}
		}
		return weaponTier >= num && weaponTier <= league;
	}
}
